<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>英文文章打字练习</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background-color: #f0f0f0; }
        #header { text-align: center; margin-bottom: 30px; }
        #exercise-container { background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        #target-text { font-size: 18px; line-height: 1.6; margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        #input-text { width: 100%; height: 100px; padding: 10px; font-size: 16px; margin-bottom: 20px; border: 2px solid #007bff; border-radius: 5px; resize: vertical; }
        #stats { display: flex; justify-content: space-around; margin-bottom: 20px; font-size: 16px; }
        .highlight { background-color: yellow; }
        .correct { color: #28a745; }
        .incorrect { color: #dc3545; text-decoration: underline; }
        button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
        button:hover { background-color: #0056b3; }
        #back-btn { background: #888; margin-bottom: 20px; }
        #back-btn:hover { background: #444; }
    </style>
</head>
<body>
    <div id="header">
        <button id="back-btn" onclick="location.href='main.html'">返回主菜单</button>
        <h1>英文文章打字练习</h1>
        <button onclick="startNewExercise()">开始新的练习</button>
    </div>
    <div id="exercise-container">
        <div id="target-text"></div>
        <textarea id="input-text" placeholder="在这里输入上面的文字..." oninput="checkInput()" disabled></textarea>
        <div id="stats">
            <div>时间: <span id="timer">0</span> 秒</div>
            <div>速度: <span id="speed">0</span> 字/分钟</div>
            <div>准确率: <span id="accuracy">0</span>%</div>
        </div>
    </div>
    <div id="history-modal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.5);z-index:999;justify-content:center;align-items:center;">
        <div style="background:#fff;padding:30px 20px;border-radius:10px;max-width:600px;width:90vw;max-height:90vh;overflow:auto;position:relative;">
            <button onclick="closeHistoryModal()" style="position:absolute;top:10px;right:10px;font-size:18px;">×</button>
            <h2>历史成绩</h2>
            <ul id="history-list"></ul>
            <div id="chart" style="width:100%;height:400px;"></div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <script>
        if (!localStorage.getItem('isLoggedIn')) { window.location.href = 'login.html'; }
        let startTime, timerInterval, originalText = "", exerciseRunning = false;
        /**
         * 获取英文文章API
         * @returns {Promise<string>} 返回一段英文段落
         */
        async function fetchArticle() {
            const response = await fetch('https://baconipsum.com/api/?type=all-meat&paras=3');
            const data = await response.json();
            return data.join('\n');
        }
        /**
         * 开始新的练习，初始化界面和数据
         */
        async function startNewExercise() {
            clearInterval(timerInterval);
            exerciseRunning = true;
            document.getElementById("input-text").value = "";
            document.getElementById("input-text").disabled = true;
            document.getElementById("target-text").textContent = "正在获取文章...";
            document.getElementById("timer").textContent = "0";
            document.getElementById("speed").textContent = "0";
            document.getElementById("accuracy").textContent = "0";
            // 获取文章
            let article = '';
            try {
                article = await fetchArticle();
            } catch (e) {
                article = "获取文章失败，请重试。";
            }
            originalText = article;
            document.getElementById("target-text").innerHTML = originalText.split("").map(char => `<span class='char'>${char}</span>`).join("");
            document.getElementById("input-text").disabled = false;
            document.getElementById("input-text").focus();
            startTime = Date.now();
            timerInterval = setInterval(updateTimer, 1000);
        }
        /**
         * 更新时间显示
         */
        function updateTimer() {
            const elapsed = Math.floor((Date.now() - startTime) / 1000);
            document.getElementById("timer").textContent = elapsed;
        }
        /**
         * 检查输入内容，标记正确/错误并统计速度和准确率
         */
        function checkInput() {
            if (!exerciseRunning) return;
            const inputText = document.getElementById("input-text").value;
            const targetSpans = document.querySelectorAll("#target-text .char");
            let correctCount = 0;
            targetSpans.forEach((span, index) => {
                const inputChar = inputText[index];
                if (!inputChar) {
                    span.classList.remove("correct", "incorrect");
                } else if (inputChar === originalText[index]) {
                    span.classList.add("correct");
                    span.classList.remove("incorrect");
                    correctCount++;
                } else {
                    span.classList.add("incorrect");
                    span.classList.remove("correct");
                }
            });
            const timeElapsed = (Date.now() - startTime) / 1000 / 60;
            const accuracy = inputText.length > 0 ? Math.round((correctCount / inputText.length) * 100) : 0;
            const speed = Math.round((inputText.length / 5) / timeElapsed) || 0;
            document.getElementById("speed").textContent = speed;
            document.getElementById("accuracy").textContent = accuracy;
            if (inputText.length === originalText.length) {
                clearInterval(timerInterval);
                exerciseRunning = false;
                saveUserHistory({
                    date: new Date().toLocaleString(),
                    speed,
                    accuracy,
                    time: Math.floor((Date.now() - startTime) / 1000)
                });
                showHistoryModal();
            }
        }
        /**
         * 获取当前用户的历史记录
         */
        function getUserHistory() {
            const user = localStorage.getItem('currentUser') || 'default';
            const data = localStorage.getItem('en_history_' + user);
            return data ? JSON.parse(data) : [];
        }
        /**
         * 保存用户历史记录
         */
        function saveUserHistory(record) {
            const user = localStorage.getItem('currentUser') || 'default';
            let history = getUserHistory();
            history.push(record);
            localStorage.setItem('en_history_' + user, JSON.stringify(history));
        }
        /**
         * 渲染历史成绩列表
         */
        function renderHistory() {
            const history = getUserHistory();
            const list = document.getElementById('history-list');
            list.innerHTML = '';
            history.slice(-10).reverse().forEach(item => {
                const li = document.createElement('li');
                li.textContent = `时间: ${item.date} | 速度: ${item.speed} 字/分钟 | 准确率: ${item.accuracy}% | 用时: ${item.time}秒`;
                list.appendChild(li);
            });
        }
        /**
         * 显示历史成绩弹窗
         */
        function showHistoryModal() {
            document.getElementById('history-modal').style.display = 'flex';
            renderHistory();
            setTimeout(() => {
                renderChart();
            }, 100);
        }
        /**
         * 关闭历史成绩弹窗
         */
        function closeHistoryModal() {
            document.getElementById('history-modal').style.display = 'none';
        }
        /**
         * 渲染成绩趋势图
         */
        function renderChart() {
            const history = getUserHistory();
            const chartDom = document.getElementById('chart');
            if (!chartDom) return;
            if (chartDom._echarts_instance_) {
                echarts.dispose(chartDom);
            }
            const myChart = echarts.init(chartDom);
            const data = history.slice(-10);
            const option = {
                title: { text: '最近10次成绩趋势' },
                tooltip: {},
                legend: { data:['速度','准确率'] },
                xAxis: {
                    type: 'category',
                    data: data.map((item, idx) => item.date.split(' ')[1] || idx+1)
                },
                yAxis: {},
                series: [
                    { name: '速度', type: 'line', data: data.map(item => item.speed) },
                    { name: '准确率', type: 'line', data: data.map(item => item.accuracy) }
                ]
            };
            myChart.setOption(option);
            setTimeout(() => { myChart.resize(); }, 0);
        }
        // 初始化历史
        renderHistory();
        renderChart();
    </script>
</body>
</html> 